package cn.itrip.common;

import cn.itrip.beans.domain.ItripUser;
import cn.itrip.beans.vo.TokenVo;
import com.alibaba.fastjson.JSONObject;

public class TokenUtil {
    private RedisAPI redisAPI;

    public RedisAPI getRedisAPI() {
        return redisAPI;
    }

    public void setRedisAPI(RedisAPI redisAPI) {
        this.redisAPI = redisAPI;
    }
    public TokenVo createToken(ItripUser user, String userAenger){
        StringBuffer buffer = new StringBuffer();
        if(UserAgentUtil.isPc(userAenger)){
            buffer.append("token:PC-");
        }else{
            buffer.append("token:mobile-");
        }
        buffer.append(MD5.md5(user.getUserCode()));
        buffer.append("-").append(user.getId());
        buffer.append("-").append(System.currentTimeMillis());
        buffer.append("-").append(MD5.md5(userAenger).substring(0,6));
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(buffer.toString());
        tokenVo.setGenTime(System.currentTimeMillis());
        tokenVo.setExpTime(System.currentTimeMillis()+7200000);
        if(UserAgentUtil.isPc(userAenger)){
            redisAPI.set(tokenVo.getToken(),7200, JSONObject.toJSONString(user));
        }else{
           redisAPI.set(tokenVo.getToken(),JSONObject.toJSONString(user));
        }
        return tokenVo;
    }
    public ItripUser getUser(String token){
        String userinfo = redisAPI.get(token);
        if(userinfo != null){
            return JSONObject.parseObject(userinfo,ItripUser.class);
        }
        return null;
    }
}
